﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace  LINQToolKit.Configuration
{
    public sealed class ContextConfiguration : ConfigurationBase
    {
        public ProviderConfiguration Provider { get; set; }
        public TypeConfiguration Request { get; set; }

        protected override void Initialize(XElement element)
        {
            var providerElement = element.Element("provider");

            if (providerElement != null)
            {
                this.Provider = new ProviderConfiguration();
                this.Provider.InitializeFromElement(providerElement);
            }

            var requestElement = element.Element("request");

            if (requestElement != null)
            {
                this.Request = new TypeConfiguration();
                this.Request.InitializeFromElement(requestElement);
            }
        }

        public static ContextConfiguration Default
        {
            get
            {
                var path = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory, "context.config");

                return Load(path);
            }
        }

        private static ContextConfiguration LoadElement(XElement doc)
        {
            ContextConfiguration config = new ContextConfiguration();
            config.InitializeFromElement(doc);

            return config;
        }

        public static ContextConfiguration Load(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            return LoadElement(XElement.Load(path));
        }

        public static ContextConfiguration LoadXml(string xml)
        {
            xml.AssertNull("xml", xml);

            return LoadElement(XElement.Parse(xml));
        }
    }
}
